<?php
//TODO 將 student_score_stage 的 class_sn 去除
// 直接參考 semester_subject 的 sn
class Score_StageController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function errorAction()
    {

    }
    /**
     * 未配課
     * @return unknown_type
     */
    public function yetAssignAction()
    {

    }

    public function indexAction()
    {
        $this->_listScore();
    }

    public function printScoreAction()
    {
        $this->_listScore();
        $this->getHelper('layout')->disableLayout();

    }

    /**
     * 列出成績
     * @return unknown_type
     */
    private function _listScore()
    {
        // 教師 sn
        $teacherSn = Teacher_Model_Teacher::getSnById();

        // 目前的學年學期
        $year = $this->view->Semester['year'];
        $semester = $this->view->Semester['semester'];

        // 取任教班級科目
        $model = new Semester_Model_SemesterTeacherCourse();
        $teacherCourse = $model->getTeacherCourse($year,$semester,$teacherSn,
        Semester_Model_SemesterTeacherCourse::SCORED);

        if (count($teacherCourse) ==0)
        $this->_redirect('score/stage/yet-assign');

        $this->view->teacherCourse = $teacherCourse;
        $sn = $this->getRequest()->getParam('sn');


        if (!$sn)
        $sn = (int) current(array_keys($teacherCourse));
        // 檢查 sn 查否在本學期配課中
        elseif (!in_array($sn, array_keys($teacherCourse)) )
        {
            $this->_redirect('score/stage/error');
        }

        // 選擇配課科目流水號
        $this->view->sn = $sn ;

        // 目前輸入階段
        $stage = $this->getRequest()->getPost('stage_id');

        // 建立階段成績 object
        $scoreStage = new Score_Model_Stage($sn,$stage);

        // 檢查是否為自己的配課
        if ($teacherSn != $scoreStage->getTeacherCourse()->teacher_sn) {
            $this->_redirect('score/stage/error');
        }

        // $this->view->scoreStage = $scoreStage;
        // 是否為分組課程
        // $this->view->isElective = $scoreStage->isElective();

        // 評量階段數
        $this->view->period = $scoreStage->getExamine()->period;

        //目前輸入的階段
        $this->view->currStage = $scoreStage->getCurrStage();

        // 各階段比率
        $this->view->ratioArr = $scoreStage->getExamine()->ratio;
        //print_r($this->view->ratioArr );
        // 取得階段平均,非全學期成績
        if ($scoreStage->getCurrStage() <  Score_Model_Stage::WHOLE_STAGE_SCORE)
        $this->view->scoreAverage = $scoreStage->getScoreAverge();

        // 階段成績
        $this->view->scores = $scoreStage->getScores();

        // 是否傳送
        $this->view->sendmit = $scoreStage->getSendmit();

        // 修改狀態
        $this->view->editMode = $this->getRequest()->getParam('editMode');

        // 本學期學生名冊
        $this->view->students = $scoreStage->getStudents();

        // 標題
        $this->view->headTitle()->prepend(
        $this->view->class_arr[$teacherCourse[$sn]['grade'].'-'.$teacherCourse[$sn]['class_sn']].' '.
        $teacherCourse[$sn]['name']);
        // 科目名稱
        $this->view->subjectName = $this->view->class_arr[$teacherCourse[$sn]['grade'].'-'.$teacherCourse[$sn]['class_sn']].' '.
        $teacherCourse[$sn]['name'];
    }

    /**
     * 儲存
     * @return unknown_type
     */
    public function saveAction()
    {
        $sn = $this->getRequest()->getPost('sn');
        $stage = (int) $this->getRequest()->getPost('stage_id');
        $teacherSn = Teacher_Model_Teacher::getSnById();
        // 建立階段成績 object
        $scoreStage = new Score_Model_Stage($sn,$stage);
        // 檢查是否為自己的配課
        if ($teacherSn != $scoreStage->getTeacherCourse()->teacher_sn) {
            $this->_redirect('score/stage/error');
        }


        $scores = $this->getRequest()->getPost('score');
        $scoreStage->save($stage , $scores);


        $this->_redirect('score/stage/index/sn/'.$sn);
    }

    //TODO 分組班匯到教務處處理
    // 記錄到 student_score_elective_stage
    /**
    * 匯到教務處
    *
    * @return unknown_type
    */
    public function exportAction()
    {
        $sn = $this->getRequest()->getPost('sn');
        $stage = (int)$this->getRequest()->getPost('stage_id');
        $teacherSn = Teacher_Model_Teacher::getSnById();
        // 建立階段成績 object
        $scoreStage = new Score_Model_Stage($sn,$stage);
        // 檢查是否為自己的配課
        if ($teacherSn != $scoreStage->getTeacherCourse()->teacher_sn) {
            $this->_redirect('score/stage/error');
        }
        // 如果為分組班,先找出學生的 sn
        if ($scoreStage->isElective()) {

            $q = Doctrine_Query::create()
            ->select('s.student_sn')
            ->from('Student_Model_StudentScoreElectiveStudent s')
            ->leftJoin('s.Student_Model_StudentScoreElectiveGroup g')
            ->where('g.teacher_course_sn=?',$scoreStage->getTeacherCourse()->sn );
            foreach($q->fetchArray() as $row)
            $studentArr[] = $row['student_sn'];
            // 設定為已傳送
            $q = Doctrine_Query::create()
            ->update('Student_Model_StudentScoreElectiveStage')
            ->set('sendmit', '?','Y')
            ->set('teacher_sn','?', $teacherSn)
            ->where('group_sn = (SELECT sn FROM Student_Model_StudentScoreElectiveGroup
              WHERE teacher_course_sn=?)', $scoreStage->getTeacherCourse()->sn)
            ->Where('test_sort=?', $stage);
            $q->execute();

        }
        else {
            // 設定為已傳送
            $q = Doctrine_Query::create()
            ->update('Student_Model_StudentScoreStage')
            ->set('sendmit', '?','Y')
            ->set('teacher_sn','?', $teacherSn)
            ->where('subject_sn=?', $scoreStage->getTeacherCourse()->subject_sn)
            ->andWhere('class_sn=?', $scoreStage->getTeacherCourse()->class_sn)
            ->andWhere('test_sort=?', $stage);
            $q->execute();
        }
        // 評量階段數
        $period = $scoreStage->getExamine()->period;

        $arr = array();
        // 全學期成績或已輸入所有階段成績,結算到全學期成績
        if ($stage ==  Score_Model_Stage::WHOLE_STAGE_SCORE ) {
            $q = Doctrine_Query::create()
            ->select('a.student_sn , a.score, b.test_kind AS test_kind')
            ->from ('Student_Model_StudentScoreStageDetail a')
            ->leftJoin('a.Student_Model_StudentScoreStage b')
            ->where('b.subject_sn=?',$scoreStage->getTeacherCourse()->subject_sn)
            ->andWhere('b.test_sort=?',$stage);
            if ($scoreStage->isElective())
            $q->whereIn('a.student_sn',$studentArr);
            else
            $q->andWhere('b.class_sn=?', $scoreStage->getTeacherCourse()->class_sn);
            $q->groupBy('a.student_sn');
            $res = $q->fetchArray();

            foreach($res as $row) {
                $arr[$row['student_sn']] += $row['score']  ;
            }
        }
        elseif ($stage == $period) {
            $ratio = $scoreStage->getExamine()->ratio;
            $q = Doctrine_Query::create()
            ->select('a.student_sn , a.score, b.test_kind AS test_kind, b.test_sort AS test_sort')
            ->from ('Student_Model_StudentScoreStageDetail a')
            ->leftJoin('a.Student_Model_StudentScoreStage b')
            ->where('b.subject_sn=?',$scoreStage->getTeacherCourse()->subject_sn);
            if ($scoreStage->isElective())
            $q->whereIn('a.student_sn',$studentArr);
            else
            $q->andWhere('b.class_sn=?', $scoreStage->getTeacherCourse()->class_sn);

            $q->groupBy('a.student_sn, b.test_kind, b.test_sort');
            $res = $q->fetchArray();

            $totalRatio = 0;
            foreach($ratio as $val) {
                if (is_array($val))
                foreach($val as $vals)
                $totalRatio += $vals;
            }

            // 比率計算
            foreach($res as $row) {
                if(!isset($arr[$row['student_sn']]))
                $arr[$row['student_sn']] = 0;
                $arr[$row['student_sn']] += ($ratio[$row['test_sort']][$row['test_kind']] / $totalRatio) * $row['score'] ;
            }
        }
        if ($arr) {
            //            echo '<pre>';print_r($studentArr);
            //            echo '<hr>';
            //            print_r($res);print_r($arr) ; exit;
            foreach($arr as $studentSn=>$score) {
                $studentScoreSemester =  new Student_Model_StudentScoreSemester() ;
                $q = Doctrine_Query::create()
                ->select('sn')
                ->from('Student_Model_StudentScoreSemester')
                ->where('student_sn=?', $studentSn )
                ->andWhere('subject_sn=?', $scoreStage->getTeacherCourse()->subject_sn);
                $sres = $q->fetchOne();
                if ($sres)
                $studentScoreSemester->assignIdentifier($sres->sn);
                $studentScoreSemester->student_sn = $studentSn;
                $studentScoreSemester->subject_sn = $scoreStage->getTeacherCourse()->subject_sn;
                $studentScoreSemester->score = $score;
                $studentScoreSemester->teacher_sn = $teacherSn;
                $studentScoreSemester->save();
            }
        }

        $this->_redirect('score/stage/index/sn/'.$sn);
    }

}
